package com.gateway.server.listener.nacos;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.exception.NacosException;
import com.gateway.common.constant.NacosPathConstants;
import com.gateway.common.exception.GatewayException;
import com.gateway.common.utils.JsonUtils;
import com.gateway.server.listener.AbstractListDataChangedListener;
import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: ahcloud-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2023/2/6 16:22
 **/
public class NacosDataChangedListener extends AbstractListDataChangedListener {
    private static final Logger log = LoggerFactory.getLogger(NacosDataChangedListener.class);

    private final ConfigService configService;

    public NacosDataChangedListener(final ConfigService configService) {
        super(new ChangeData(NacosPathConstants.ROUTE_DATA_ID));
        this.configService = configService;
    }

    @Override
    protected void publishConfig(String dataId, Object data) {
        try {
            configService.publishConfig(
                    dataId,
                    NacosPathConstants.GROUP,
                    JsonUtils.toJsonString(data),
                    ConfigType.JSON.getType()
            );
        } catch (NacosException e) {
            log.error("Publish data to nacos error, reason is {}", Throwables.getStackTraceAsString(e));
            throw new GatewayException(e.getMessage());
        }
    }
}
